<template>
	<view class="container">
		<view>
			<view class="cart-list" v-if="cartData && cartData.length > 0">
				<view v-for="(item, index) in cartData" :key="index">
					<view class="cart-item">
						<image class="checkbox" @click="checkedHandle(index)" :src="checkeds.indexOf(index) === -1 ? '../../static/langwen/radio.png' : '../../static/langwen/checked.png'" mode=""></image>
						<view class="goods">
							<image class="goods-img" :src="item.productPic" mode=""></image>
							<view class="goods-intro">
								<view class="goods-title">{{ item.productName }}</view>
								<view class="goods-description" @click="handleSku(index)">
									{{ (item.sp1||'') + (item.sp2||'') + (item.sp3||'') + (item.sp4 || '') }}
                                    <image :class="popupShow ? 'arrow arrow-reverse' : 'arrow'" src="../../static/langwen/arrow_bottom.png"></image>
								</view>
								<view class="goods-price">
									¥{{ item.price }}
								</view>
								<view class="goods-quantity">
									<image class="btn" src="../../static/langwen/reduce.png" @click.stop="numLess(index)" mode=""></image>
									<view class="number">{{ item.quantity }}</view>
									<image class="btn" src="../../static/langwen/add.png" @click.stop="numAdd(index)" mode=""></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
            <view class="cart-tips" v-else>当前购物车没有商品,快去选择吧</view>
			<view class="recommend" v-if="recommendGoods.length">
				<view class="header">
					<view class="title">
						推荐商品
					</view>
					<!-- <view class="right-btn">
						查看全部
						<image class="img" src="../../static/langwen/arrow_right_3.png" mode=""></image>
					</view> -->
				</view>
				<view class="main">
					<item v-for="(item,index) in recommendGoods" :item="item" :key="index"></item>
				</view>
			</view>
			<view class="fixed-bottom" v-show="!isEdit">
				<div class="fixed-bottom-left" @click="allChecked = !allChecked">
                    <image class="goods-total-select" 
                    :src="allChecked ? '../../static/langwen/checked.png' : '../../static/langwen/radio.png'" mode=""></image>
                    <view class="goods-total-select-txt">
                        全选
                    </view>
                    <view class="goods-total-price">
                        应付金额:<text class="goods-total-price-onrange">¥{{ totalPrice }}</text>
                    </view>
                </div>
				<view class="goods-pay-btn" @click="payHandle">
					结算
				</view>
			</view>
            <view class="fixed-bottom" v-show="isEdit">
				<div class="fixed-bottom-left" @click="allChecked = !allChecked">
                    <image class="goods-total-select" 
                    :src="allChecked ? '../../static/langwen/checked.png' : '../../static/langwen/radio.png'" mode=""></image>
                    <view class="goods-total-select-txt">
                        全选
                    </view>
                </div>
				<view class="goods-pay-btn" @click="deleteHandle">
					删除
				</view>
			</view>
            <popup v-if="popupShow" :id="cartData[skuIndex].productId" type="2" :goodsNum="cartData[skuIndex].quantity" :selected="selected" v-on:close-popup="closePopup" ></popup>
		</view>
	</view>
</template>

<script>
import Api from '@/common/api';
import demoData from '@/common/demoData';
import item from '@/components/langwen/item.vue';
import popup from '@/components/langwen/popup.vue';
export default {
	name: 'cart',
    onShow() {
        // 获取购物车数据
        this.getCartData();
        // 获取购物车推荐商品数据, 目前没有接口
        this.getRecommendGoods();
        this.$clound.cloudEvent('hideExistFrm');
    },
    onHide() {
        this.$clound.cloudEvent('showExistFrm');
    },
    onUnload() {
        this.$clound.cloudEvent('showExistFrm');
    },
	components: {
        item,
        popup
	},
	data() {
		return {
            cartData: '', // 购物车数据
            isEdit: false, // 是否点击编辑
            checkeds: [], // 选中的商品
            allChecked: false, //全选状态  true|false
            recommendGoods: [], // 推荐商品
            popupShow: false, // 规格弹窗是否显示
            skuIndex: -1
		}
    },
    computed: {
        // 计算选中的总金额
        totalPrice() {
            var price = 0;
            this.checkeds.forEach((item) => {
                let cartItem = this.cartData[item];
                price += cartItem.price * cartItem.quantity;
            });
            return price.toFixed(2);
        },
        // 选中的商品id, 用逗号拼接
        goodsIds() {
            var ids = [];
            this.checkeds.forEach((item) => {
                ids.push(this.cartData[item].id);
            });
            return ids.join(',');
        },
        // 商品ID
        productIds() {
            var ids = [];
            this.checkeds.forEach((item) => {
                ids.push(this.cartData[item].productId);
            });
            return ids.join(',');
        }
    },
    methods: {
        handleSku(index) {
            this.skuIndex = index;
            this.popupShow = true;
        },
        closePopup(selected, num) {
            // 关闭规格弹窗
            this.popupShow = false;
            let goods = this.cartData[this.skuIndex];
            goods.sp1 = selected.sp1;
            goods.sp2 = selected.sp2;
            goods.sp3 = selected.sp3;
            goods.sp4 = selected.sp4;
            goods.productSkuId = selected.id;
            goods.productPic = selected.pic;
            goods.price = selected.price;
			this.$set(goods, 'quantity', num);
			this.changeQuantity(goods.id,goods.quantity);
            this.cartData[this.skuIndex] = goods;
            this.changeGoodsSku(this.skuIndex);
        },
        numLess(index) {
            // 购买数量减1
            if(this.cartData[index].quantity > 1) {
                let num = this.cartData[index].quantity - 1;
                this.$set(this.cartData[index], 'quantity', num);
                this.changeQuantity(this.cartData[index].id,this.cartData[index].quantity);
            }
        },
        numAdd(index) {
            // 购买数量加1
            let num = this.cartData[index].quantity + 1;
            this.$set(this.cartData[index], 'quantity', num);
            this.changeQuantity(this.cartData[index].id,this.cartData[index].quantity);
        },
        async getCartData() {
            // 获取购物车列表数据
            var params = {};
            var data = await Api.apiCall('get', Api.goods.cartList, params);
            this.cartData = data.cartItemList;
        },
        checkedHandle(index) {
            // 点击商品
            var oldIndex = this.checkeds.indexOf(index);
            if(oldIndex === -1) {
                this.checkeds.push(index);
            } else {
                this.checkeds.splice(oldIndex, 1);
            }
        },
        async deleteHandle() {
            // 删除商品
			if(!this.goodsIds) {
				this.$api.msg('请先选择商品');
				return;
			};
            var params = {
                'cart_id_list': this.goodsIds
            };
            var data = await Api.apiCall('get', Api.goods.deleteGoods, params);
			this.getCartData();
			this.checkeds = [];
			this.allChecked = false;
			this.$api.msg('删除成功');
			this.isEdit = false;
        },
        async payHandle() {
            // 结算
            if(!this.goodsIds) {
                this.$api.msg('请先选择商品');
                return;
            }
            var params = {
                'type': '2',
                'source': '2',
                'orderType': '1',
                'cartIds': this.goodsIds
            };
            var data = await Api.apiCall('get', Api.goods.priviewOrder, params);
            if(!data) return;
            // 路径
            var url = '/pages/langwen/confirm';
            // 参数
            params.orderInfo = data;
			this.checkeds = [];
			this.allChecked = false;
            uni.navigateTo({
                url: `${url}?param=${encodeURIComponent(JSON.stringify(params))}`
            });
        },
        async getRecommendGoods() {
            // 获取推荐商品
            var params = {};
            var data = await Api.apiCall('get', Api.goods.cartRelatedGoods, params);
            this.recommendGoods = data;
        },
        // 改变商品数量
        changeQuantity(id, quantity) {
            var params = {
                // 购物车明细项ID
                'id': id,
                'quantity': quantity 
            };
            var data = Api.apiCall('get', Api.goods.changeQuantity, params);
        },
        // 改变规格
        changeGoodsSku(index) {
            let goods = this.cartData[index];
            var params = {
                // 购物车明细项ID
                'id': goods.id,
                'productId': goods.productId,
                'quantity': goods.quantity,
                'productSkuId': goods.productSkuId,
                'price': goods.price,
                'checked': 1
            };
            var data = Api.apiCall('get', Api.goods.changeSku, params);
            this.skuIndex = -1;
        }
    },
    onNavigationBarButtonTap() {
        this.isEdit = !this.isEdit;
    },
    watch: {
        isEdit() {
            var btnName = '';
            var uniBtnIcon = document.getElementsByClassName('uni-btn-icon')[1];
            if(this.isEdit) {
                btnName = '取消';
            } else {
                btnName = '编辑';
            }
            uniBtnIcon.innerText = btnName;
        },
        allChecked() {
            if(this.allChecked) {
                this.checkeds = [];
                for(let i = 0; i < this.cartData.length; i++) {
                    this.checkeds.push(i);
                }
            } else {
                this.checkeds = [];
            }
        }
    }
};
</script>

<style lang="scss">
page {
	position: relative;
	background:rgba(245,245,245,1);
	padding: 0 15px;
}
.container {
	padding-bottom: 60px;
	/* 空白页 */
	.empty {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100vh;
		padding-bottom: 100upx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		background: #fff;
		image {
			width: 240upx;
			height: 160upx;
			margin-bottom: 30upx;
		}
		.empty-tips {
			display: flex;
			font-size: $font-sm + 2upx;
			color: $font-color-disabled;
			.navigator {
				color: $uni-color-primary;
				margin-left: 16upx;
			}
		}
	}
}
/* 购物车列表项 */
.cart-item {
	position: relative;
	display: flex;
	align-items: center;
	margin: 10px 0;
	padding: 15px;
	background:rgba(255,255,255,1);
	box-shadow:0px 1px 8px 0px rgba(0,0,0,0.02);
	border-radius:8px;
	.checkbox {
		width: 22px;
		height: 22px;
		min-width: 22px;
		margin-right: 15px;
	}
	.checked {
		width: 22px;
		height: 22px;
		min-width: 22px;
		margin-right: 15px;
	}
	.goods {
		flex-grow: 1;
		display: flex;
        overflow: hidden;
		.goods-img {
			width: 60px;
			height: 80px;
			margin-right: 12px;
			min-width: 60px;
		}
		.goods-intro {
			flex-grow: 1;
            overflow: hidden;
			.goods-title {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                width: 100%;
				font-size:14px;
				font-weight:400;
				color:rgba(51,51,51,1);
			}
			.goods-description {
                display: flex;
                align-items: center;
				width: fit-content;
				font-size:12px;
				font-weight:400;
				color:rgba(191,191,191,1);
				margin-top: 10px;
                .arrow {
                    width: 16rpx;
                    height: 16rpx;
                    margin-left: 10rpx;
                }
                .arrow-reverse {
                    transform: rotate(180deg);
                }
			}
			.goods-price {
				font-size:14px;
				font-weight:600;
				color:rgba(255,101,24,1);
				margin-top: 10px;
			}
			.goods-quantity {
				position: absolute;
				right: 15px;
				bottom: 20px;
				width: 81px;
				height: 22px;
				border:1px solid rgba(212,215,224,1);
				display: flex;
				justify-content: space-between;
				.btn {
					width: 20px;
					min-width: 20px;
					height: 20px;
					text-align: center;
				}
				.number {
					width: 37px;
					border-left:1px solid rgba(212,215,224,1);
					border-right:1px solid rgba(212,215,224,1);
					text-align: center;
					font-size:14px;
					font-weight:400;
					color:rgba(63,64,70,1);
				}
			}
		}
	}
}

.recommend {
	margin: 0 -15px;
	background:rgba(255,255,255,1);
	box-shadow:0px 1px 8px 0px rgba(0,0,0,0.02);
	border-radius:6px;
	.header {
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.title {
			font-size:16px;
			font-weight:500;
			color:rgba(51,51,51,1);
		}
		.right-btn {
			display: flex;
			align-items: center;
			font-size:13px;
			font-weight:400;
			color:rgba(153,153,153,1);
			.img {
				width: 15px;
				height: 15px;
			}
		}
	}
	.main {
		display: flex;
		padding-bottom: 15px;
		overflow: auto;
		.item {
            margin: 0 15px;
            &:last-child {
                padding-right: 15px;
            }
		}
	}
}
.fixed-bottom {
	z-index: 100;
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: fixed;
	left: 0;
	bottom: 50px;
	width: 100%;
	height: 50px;
	border-top: 1rpx solid rgb(212,212,212);
	border-bottom: 1rpx solid rgb(212,212,212);
	background:rgba(255,255,255,1);
	box-shadow:0px 1px 0px 0px rgba(213,216,225,1);
}

.fixed-bottom-left {
    display: flex;
    align-items: center;
}

.goods-total-select {
	width:22px;
	height:22px;
	margin: 0 7px 0 15px;
}

.goods-total-select-txt {
	font-size:15px;
	font-weight:400;
	color:rgba(51,51,51,1);
}

.goods-total-price {
    display: flex;
    align-items: center;
	font-size:15px;
	font-weight:400;
	color:rgba(127,129,141,1);
	margin-left: 10px;
}

.goods-total-price-onrange {
	font-weight:500;
	color: rgba(255,101,24,1);
	margin-left: 5px;
}

.goods-pay-btn {
	display: flex;
	justify-content: center;
	align-items: center;
	width:100px;
	height:50px;
	background:rgba(253,155,67,1);
	font-size:16px;
	font-weight:400;
	color:rgba(255,255,255,1);
	margin-top: -1px;
}

.cart-tips {
    font-size: 30rpx;
    margin-top: 120rpx;
	margin-bottom: 120rpx;
    text-align: center;
}
</style>
